package model

import (
	"time"
)

type Msg struct {
	Id int
	Title string
	Content string
	Uid int
	CTime time.Time
}

func (self *Msg) Query() ([]*Msg, error) {
	query := "select id,title,content,uid,ctime from test.msg"
	rows,err := db.Query(query)
	if err != nil {
		return nil,err
	}
	var msgs []*Msg
	for rows.Next() {
		var id int
		var title string
		var content string
		var uid int
		var ctime time.Time
		err = rows.Scan(&id, &title, &content, &uid, &ctime)
		if err != nil {
			continue
		}
		msgs = append(msgs, &Msg{id,title,content,uid,ctime})
	}
	return msgs,nil
}

func (self *Msg) Save() (int64, error)  {
	query := "insert into test.msg (id,title,content,uid,ctime) values (?,?,?,?,?)"
	state,err := db.Prepare(query)
	defer state.Close()
	if err != nil {
		return -1,err
	}
	res,err := state.Exec(self.Id,self.Title,self.Content,self.Uid,self.CTime)
	if err != nil {
		return -1, err
	}
	num,err := res.RowsAffected()
	if err != nil {
		return -1, err
	}
	return num,nil
}

func (self *Msg) GetById() (*Msg, error)  {
	query := "select id,title,content,uid,ctime from test.msg where id = ?"
	rows := db.QueryRow(query, self.Id)
	var id int
	var title string
	var content string
	var uid int
	var ctime time.Time
	err := rows.Scan(&id, &title, &content, &uid, &ctime)
	if err != nil {
		return nil, err
	}
	return &Msg{Id:id,Title:title,Content:content,Uid:uid,CTime:ctime}, nil
}
